<?php

/* 会员控制器 */

class UserApp extends BackendApp {

    var $_admin_mod;
    var $_member_mod;
    var $_store_mod;

    function __construct() {
        $this->UserApp();
    }

    function UserApp() {
        parent::__construct();
        $this->_member_mod = & m('member');
        $this->_admin_mod = & m('userpriv');
        $this->_store_mod = &m('store');
    }

    function index() {
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => $_GET['field_name'],
                'name' => 'field_value',
                'equal' => 'like',
            ),array(
                'field' => 'reg_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'reg_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),
        ));
        //更新排序
        if (isset($_GET['sort']) && !empty($_GET['order'])) {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc'))) {
                $sort = 'user_id';
                $order = 'desc';
            }
        } else {
            if (isset($_GET['sort']) && empty($_GET['order'])) {
                $sort = strtolower(trim($_GET['sort']));
                $order = "";
            } else {
                $sort = 'user_id';
                $order = 'desc';
            }
        }

        //搜索店铺归属信息
        if(isset($_GET['store_id']) && $_GET['store_id']){
            $conditions .= ' AND second_class = '.$_GET['store_id'].' OR first_class = '.$_GET['store_id'].' OR s_id ='.$_GET['store_id'];
            $this->assign('store_id',$_GET['store_id']);
        }

        $page = $this->_get_page(50);
        $users = $this->_member_mod->find(array(
            'join' => 'has_store,manage_mall',
            'fields' => 'this.*,store.store_id,userpriv.store_id as priv_store_id,userpriv.privs',
            'conditions' => '1=1' . $conditions,
            'limit' => $page['limit'],
            'order' => "$sort $order",
            'count' => true,
        ));
        foreach ($users as $key => $val) {
            if ($val['priv_store_id'] == 0 && $val['privs'] != '') {
                $users[$key]['if_admin'] = true;
            }
            if($val['second_class']){
                $users[$key]['storeInfo'] = $this->_store_mod->get(array("conditions"=>"store_id = ".$val['second_class']));
                if($val['first_class'] > 2 && $val['second_class'] == 0 ){
                    $users[$key]['storeInfo'] = $this->_store_mod->get(array("conditions"=>"store_id = ".$val['first_class']));
                }elseif($val['first_class'] == 2 && $val['second_class']){
                    $users[$key]['storeInfo'] = $this->_store_mod->get(array("conditions"=>"store_id = ".$val['second_class']));
                }
            }
            if($val['first_class'] && $val['second_class'] == 0){
                $users[$key]['storeInfo'] = $this->_store_mod->get(array("conditions"=>"store_id = ".$val['first_class']));
            }
            if(!$users[$key]['storeInfo']){
                $users[$key]['storeInfo']['store_name'] = $val['s_name'];
            }

        }
        $this->assign('users', $users);
        $page['item_count'] = $this->_member_mod->getCount();
        $this->_format_page($page);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);
        /* 导入jQuery的表单验证插件 */
        $this->import_resource(array(
            'script' => 'jqtreetable.js,inline_edit.js',
            'style' => 'res:style/jqtreetable.css'
        ));
        $this->assign('query_fields', array(
            'user_name' => LANG::get('user_name'),
            'email' => LANG::get('email'),
            'real_name' => LANG::get('real_name'),
            'phone_mob' => LANG::get('phone_mob'),
        ));
        $this->assign('sort_options', array(
            'reg_time DESC' => LANG::get('reg_time'),
            'last_login DESC' => LANG::get('last_login'),
            'logins DESC' => LANG::get('logins'),
        ));
        $storeList = $this->_store_mod->find(array('conditions'=>"1=1"));
        $this->assign('store',$storeList);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->assign('if_system_manager', $this->_admin_mod->check_system_manager($this->visitor->get('user_id')) ? 1 : 0);
        $this->display('user.index.html');
    }


    function iframe() {
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => $_GET['field_name'],
                'name' => 'field_value',
                'equal' => 'like',
            ),
        ));
        //更新排序
        if (isset($_GET['sort']) && !empty($_GET['order'])) {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc'))) {
                $sort = 'user_id';
                $order = 'desc';
            }
        } else {
            if (isset($_GET['sort']) && empty($_GET['order'])) {
                $sort = strtolower(trim($_GET['sort']));
                $order = "";
            } else {
                $sort = 'user_id';
                $order = 'desc';
            }
        }
        $page = $this->_get_page(50);
        $users = $this->_member_mod->find(array(
            'join' => 'has_store,manage_mall',
            'fields' => 'this.*,store.store_id,userpriv.store_id as priv_store_id,userpriv.privs',
            'conditions' => '1=1' . $conditions,
            'limit' => $page['limit'],
            'order' => "$sort $order",
            'count' => true,
        ));
        foreach ($users as $key => $val) {
            if ($val['priv_store_id'] == 0 && $val['privs'] != '') {
                $users[$key]['if_admin'] = true;
            }
        }
        $this->assign('users', $users);
        $page['item_count'] = $this->_member_mod->getCount();
        $this->_format_page($page);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);
        /* 导入jQuery的表单验证插件 */
        $this->import_resource(array(
            'script' => 'jqtreetable.js,inline_edit.js',
            'style' => 'res:style/jqtreetable.css'
        ));
        $this->assign('query_fields', array(
            'user_name' => LANG::get('user_name'),
            'email' => LANG::get('email'),
            'real_name' => LANG::get('real_name'),
            'phone_mob' => LANG::get('phone_mob'),
        ));
        $this->assign('sort_options', array(
            'reg_time DESC' => LANG::get('reg_time'),
            'last_login DESC' => LANG::get('last_login'),
            'logins DESC' => LANG::get('logins'),
        ));
        $this->assign('if_system_manager', $this->_admin_mod->check_system_manager($this->visitor->get('user_id')) ? 1 : 0);
        $this->display('user.iframe.html');
    }
    //增加用户资金   
    function money_add() {
        $user_id = !empty($_GET['id']) ? intval($_GET['id']) : 0;
        if (empty($user_id)) {
            $this->show_message('error', 'back_list', 'index.php?app=account_log');
            return;
        }
        if ($_POST) {
			if(!$_SESSION['repeat_prevent'][$_POST['repeat_prevent']]){
                $this->show_warning('重复操作！');return;
            }
            if($_SESSION['repeat_prevent'][$_POST['repeat_prevent']]>(gmtime()-5)){
                $this->show_warning('操作时间小于5秒！');return;
            }
            unset($_SESSION['repeat_prevent'][$_POST['repeat_prevent']]);
            $post_money = round($_POST['post_money'], 2);
            $jia_or_jian = trim($_POST['jia_or_jian']);
            $log_text = trim($_POST['log_text']);
            if (empty($post_money) || empty($jia_or_jian)) {
                $this->show_warning('cuowu_notnull');
                return;
            }
            if (preg_match("/[^0.-9]/", $post_money)) {
                $this->show_warning('cuowu_nishurudebushishuzilei');
                return;
            }
            
            if ($jia_or_jian == "jia") {
                $money_flow = 'income';
            } elseif ($jia_or_jian == "jian") {
                $money_flow = 'outlay';
            } else {
                $this->show_warning('cuowu_moeny_low');
                return;
            }
            //写入LOG记录
            $order_sn = date('YmdHis', gmtime() + 8 * 3600) . rand(1000, 9999);

            //给用户新增或者减少金额
            $data = array(
                'user_id' => $user_id,
                'order_sn' => $order_sn,
                'type' => ACCOUNT_TYPE_ADMIN,
                'money_flow' => $money_flow,
                'money' => $post_money,
                'states' => 40,
                'complete' => 1,
                'log_text' => $log_text,
                'add_time' => gmtime(),
            );
            $this->_member_mod->db->query('start transaction');
            $mysql_flag=$this->_member_mod->change_money($data);
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');return;
            }else{
                $this->_member_mod->db->query('commit');
            }
            $this->admin_log(Lang::get('Modified_user_value'),1);
            $this->show_message('add_money_ok', 'back_list', 'index.php?app=account_log');
            return;
        } else {
			$repeat_prevent=gmtime().rand(100, 999);
            $_SESSION['repeat_prevent'][$repeat_prevent]=gmtime();
            $this->assign('repeat_prevent',$repeat_prevent);
            $member = $this->_member_mod->get($user_id);
            if (empty($member)) {
                $this->show_warning('cuowu_no_user');
                return;
            }
            $this->assign('member', $member);
            $this->display('user.money_add.html');
        }
        return;
    }

    function super_login() {
        $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        $_SESSION['super_user_id'] = $user_id;
        $url = 'Location:' . SITE_URL . '/index.php?app=member';
        $this->admin_log(Lang::get('login_atore'),1);
        header($url);
    }

    function add() {
        if (!IS_POST) {
            $this->assign('user', array(
                'gender' => 0,
            ));
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));

            //获取会员等级信息 by qufood
            $ugrade_mod = &m('ugrade');
            $ugrades = $ugrade_mod->get_option('grade_name');
            $this->assign('ugrades', $ugrades);
            //

            $ms = & ms();
            $this->assign('set_avatar', $ms->user->set_avatar());
            $this->display('user.form.html');
        } else {
            $user_name = trim($_POST['user_name']);
            $password = trim($_POST['password']);
            $zf_pass = trim($_POST['zf_pass']);
            $email = trim($_POST['email']);
            $real_name = trim($_POST['real_name']);
            $gender = trim($_POST['gender']);
            $im_qq = trim($_POST['im_qq']);

            if (strlen($user_name) < 3 || strlen($user_name) > 25) {
                $this->show_warning('user_name_length_error');

                return;
            }

            if (strlen($password) < 6 || strlen($password) > 20) {
                $this->show_warning('password_length_error');
                return;
            }
            if (strlen($zf_pass) < 6 || strlen($zf_pass) > 20) {
                $this->show_warning('password_length_error');
                return;
            }

            if (!is_email($email)) {
                $this->show_warning('email_error');

                return;
            }



            /* 连接用户系统 */
            $ms = & ms();

            /* 检查名称是否已存在 */
            if (!$ms->user->check_username($user_name)) {
                $this->show_warning($ms->user->get_error());

                return;
            }

            /* 保存本地资料 */
            $data = array(
                'real_name' => $_POST['real_name'],
                'gender' => $_POST['gender'],
                'phone_mob' => $_POST['phone_mob'],
                'im_qq' => $_POST['im_qq'],
				'email' => $email,
                'reg_time' => gmtime(),
                'zf_pass' => md5($zf_pass),
            );

            /* 到用户系统中注册 */
            $user_id = $ms->user->register($user_name, $password,$email, $data);
            if (!$user_id) {
                $this->show_warning($ms->user->get_error());
                return;
            }else{
                $this->admin_log("新增用户[".$_POST['user_name']."]",1);
            }

            if (!empty($_FILES['portrait'])) {
                $portrait = $this->_upload_portrait($user_id);
                if ($portrait === false) {
                    return;
                }
                $portrait && $this->_member_mod->edit($user_id, array('portrait' => $portrait));
            }
            $this->show_message('add_ok', 'back_list', 'index.php?app=user', 'continue_add', 'index.php?app=user&amp;act=add'
            );
        }
    }

    /* 检查会员名称的唯一性 */

    function check_user() {
        $user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
        if (!$user_name) {
            echo ecm_json_encode(false);
            return;
        }

        /* 连接到用户系统 */
        $ms = & ms();
        echo ecm_json_encode($ms->user->check_username($user_name));
    }

    function edit() {
        $ugrade_mod = &m('ugrade');

        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        //判断是否是系统初始管理员，如果是系统管理员，必须是自己才能编辑，其他管理员不能编辑系统管理员
        if ($this->_admin_mod->check_system_manager($id) && !$this->_admin_mod->check_system_manager($this->visitor->get('user_id'))) {
            $this->show_warning('system_admin_edit');
            return;
        }
        if (!IS_POST) {
            /* 是否存在 */
            $user = $this->_member_mod->get_info($id);
            if (!$user) {
                $this->show_warning('user_empty');
                return;
            }

            //获取会员等级信息 by qufood
            $member_mod = &m('member');
            $user = $user + $member_mod->get_grade_info($id);
            $ugrades = $ugrade_mod->get_option('grade_name');
            $this->assign('ugrades', $ugrades);

            $ms = & ms();
            $this->assign('set_avatar', $ms->user->set_avatar($id));
            $this->assign('user', $user);
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            $this->display('user.form.html');
        } else {
            $data = array(
                'real_name' => $_POST['real_name'],
                'gender' => $_POST['gender'],
//                'phone_mob' => $_POST['phone_mob'],
                'im_qq' => $_POST['im_qq'],
                'im_aliww'  => $_POST['im_aliww'],
                'available' => $_POST['available'],
            );

            //当输入积分大于 0 
            $point = intval($_POST['point']);
			$user = $this->_member_mod->get_info($id);
			$integral_log_mod = &m('integral_log');
            if ($point > 0) {
                
                //选项为 增加积分
                if ($_POST['point_change'] == 'inc_by') {
                    $data['integral'] = $user['integral'] + $point;
                    //$data['total_integral'] = $user['total_integral'] + $point;

                    //操作记录入积分记录
                    
                    $integral_log = array(
                        'user_id' => $user['user_id'],
                        'user_name' => $user['user_name'],
                        'point' => $point,
                        'add_time' => gmtime(),
                        'remark' => '管理员新增积分' . $point,
                        'integral_type' => INTEGRAL_ADD,
                    );
                    $integral_log_mod->add($integral_log);
                }

                //选项为 减少积分
                if ($_POST['point_change'] == 'dec_by') {
                    //如果当前的可用积分小于扣除的积分  则不做操作
                    if ($user['integral'] >= $point) {

                        $data['integral'] = $user['integral'] - $point;
                        //$data['total_integral'] = $user['total_integral'] - $point;
                        //操作记录入积分记录
                        
                        $integral_log = array(
                            'user_id' => $user['user_id'],
                            'user_name' => $user['user_name'],
                            'point' => $point,
                            'add_time' => gmtime(),
                            'remark' => '管理员扣除积分' . $point,
                            'integral_type' => INTEGRAL_SUB,
                        );
                        $integral_log_mod->add($integral_log);
                    }
                }

                

            }
            if($_POST['grade_id']){
			$ugrade_mod = &m('ugrade');
			$ugrade=$ugrade_mod->get($_POST['grade_id']);
			if(!$ugrade){
				$this->show_warning('no_membership_grade');
                return;
			}
			$data['ugrade'] = $_POST['grade_id'];
			//更新总积分
			$data['total_integral'] = $ugrade['growth_needed'];
			
                        $integral_log = array(
                            'user_id' => $user['user_id'],
                            'user_name' => $user['user_name'],
                            'point' => $ugrade['growth_needed'],
                            'add_time' => gmtime(),
                            'remark' => '管理员改变会员等级，总积分变为' . $ugrade['growth_needed'],
                            'integral_type' => ($user['total_integral']>$ugrade['growth_needed'])?INTEGRAL_SUB:INTEGRAL_ADD,
                        );
                        $integral_log_mod->add($integral_log);
        }
            if (!empty($_POST['password'])) {
                $password = trim($_POST['password']);
                if (strlen($password) < 6 || strlen($password) > 20) {
                    $this->show_warning('password_length_error');
                    return;
                }
            }
            if (!empty($_POST['zf_pass'])) {
                $zf_pass = trim($_POST['zf_pass']);
                if (strlen($zf_pass) < 6 || strlen($zf_pass) > 20) {
                    $this->show_warning('password_length_error');
                    return;
                } else {
                    $data['zf_pass'] = md5($zf_pass);
                }
            }
            if (!is_email(trim($_POST['email']))) {
                $this->show_warning('email_error');
                return;
            }

            if (!empty($_FILES['portrait'])) {
                $portrait = $this->_upload_portrait($id);
                if ($portrait === false) {
                    return;
                }
                $data['portrait'] = $portrait;
            }

            /* 修改本地数据 */
            $this->_member_mod->edit($id, $data);
            $this->admin_log(Lang::get('Modified_info'),1);
            /* 修改用户系统数据 */
            $user_data = array();
            !empty($_POST['password']) && $user_data['password'] = trim($_POST['password']);
            !empty($_POST['email']) && $user_data['email'] = trim($_POST['email']);
            !empty($_POST['phone_mob']) && $user_data['phone_mob'] = trim($_POST['phone_mob']);
            if (!empty($user_data)) {
                $ms = & ms();
//                $ms->user->edit($id, '', $user_data, true);
                if (!($ms->user->edit($id, '', $user_data, true))) {
                    $this->show_warning($ms->user->get_error());
                    return;
                }
            }

            $this->show_message('edit_ok', 'back_list', 'index.php?app=user', 'edit_again', 'index.php?app=user&amp;act=edit&amp;id=' . $id
            );
        }
    }

    function drop() {
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id) {
            $this->show_warning('no_user_to_drop');
            return;
        }
        $admin_mod = & m('userpriv');
        if (!$admin_mod->check_admin($id)) {
            $this->show_message('cannot_drop_admin', 'drop_admin', 'index.php?app=admin');
            return;
        }

        if (!$this->check_store($id)) {
            $this->show_message('cannot_drop_store', 'drop_store', 'index.php?app=store');
            return;
        }

        $ids = explode(',', $id);

        $this->_member_mod->edit($ids, array('available' => '1'));

        /* 连接用户系统，从用户系统中删除会员 
          $ms = & ms();
          if (!$ms->user->drop($ids)) {
          $this->show_warning($ms->user->get_error());
          return;
          }
         */
        $this->admin_log(Lang::get('Disabled_member'),1);
        $this->show_message('drop_ok');
    }

    //检测删除的用户是否存在店铺  如果存在 需要先删除店铺 以便删除相关多余本地图片
    function check_store($user_id) {
        $conditions = "store_id in (" . $user_id . ")";
        $store_mod = & m('store');
        return count($store_mod->find(array('conditions' => $conditions))) == 0;
    }

    /**
     * 上传头像
     *
     * @param int $user_id
     * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
     */
    function _upload_portrait($user_id) {
        $file = $_FILES['portrait'];
        if ($file['error'] != UPLOAD_ERR_OK) {
            return '';
        }

        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->addFile($file);
        if ($uploader->file_info() === false) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=user&amp;act=edit&amp;id=' . $user_id);
            return false;
        }

        $uploader->root_dir(ROOT_PATH);
        return $uploader->save('data/files/mall/portrait/' . ceil($user_id / 500), $user_id);
    }

    function refer() {
        $sql = "select * from {$this->_member_mod->table} where user_id in (select distinct referid from {$this->_member_mod->table} where referid !=0 ) AND referid=0";
        $member_list = $this->_member_mod->getAll($sql);
        foreach ($member_list as $key => $member) {
            $member_list[$key]['switchs'] = 1;
        }
        $this->assign('member_list', $member_list);
        /* 导入jQuery的表单验证插件 */
        $this->import_resource(array(
            'script' => 'jqtable.js',
            'style' => 'res:style/jqtreetable.css'
        ));
        $this->display('user.refer.html');
    }

    /* 异步去推荐人分类子元素 */

    function ajax_refer() {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (empty($id)) {
            echo ecm_json_encode(false);
            return;
        }
        $sql = "select * from {$this->_member_mod->table} where referid = " . $id;
        $member_list = $this->_member_mod->getAll($sql);
        foreach ($member_list as $key => $member) {
            $child = $this->_member_mod->getAll("select * from {$this->_member_mod->table} where referid = " . $member['user_id']);
            if (!$child || empty($child)) {

                $member_list[$key]['switchs'] = 0;
            } else {
                $member_list[$key]['switchs'] = 1;
            }
            $member_list[$key]['reg_time'] = date('Y-m-d H:i:s', $member['reg_time']);
        }
        header("Content-Type:text/html;charset=" . CHARSET);
        echo ecm_json_encode(array_values($member_list));
        return;
    }
function remove(){
    $id=intval($_GET['id']);
    $this->_member_mod->db->query('start transaction');
    //检查用户是否是店主
    $store_mod=& m('store');
    if($store=$store_mod->get($id)){
        $this->_member_mod->db->query('rollback');
        $this->show_warning('please_delete','Retrieve_store','index.php?app=store&owner_name='.$store['owner_name'].'&store_name='.$store['store_name']);
        return;
    }
    //检查用户是否有未完成的订单
    $order_mod=& m('order');
    if($order_mod->get('buyer_id='.$id.' AND status NOT IN('.ORDER_FINISHED.','.ORDER_CANCELED.')')){
        $this->_member_mod->db->query('rollback');
        $this->show_warning('has_not_finished');
        return;
    }
    //检查用户余额
    $member=$this->_member_mod->get($id);
    if(($member['money'] != 0) || ($member['money_dj'] != 0)){
        $this->_member_mod->db->query('rollback');
        $this->show_warning('cannot_operate');
        return;
    }
    //将用户表推荐id置0
    $this->_member_mod->edit('referid='.$id,'referid=0');
    if(!$this->_member_mod->drop($id)){
        $this->_member_mod->db->query('rollback');
        $this->show_warning('del_fail');
        return;
    }
    $this->_member_mod->db->query('commit');
    $this->del_DirAndFile(ROOT_PATH."/data/files/user_".$id);
    $this->admin_log(Lang::get('del_member'),1);
    $this->show_message('del_success');
}
    function del_DirAndFile($dirName) {
        if (is_dir($dirName)) {
            if ($handle = opendir("$dirName")) {
                while (false !== ( $item = readdir($handle) )) {
                    if ($item != "." && $item != "..") {
                        if (is_dir("$dirName/$item")) {
                            $this->del_DirAndFile("$dirName/$item");
                        } else {
                            unlink("$dirName/$item");
                        }
                    }
                }
                closedir($handle);
                rmdir($dirName);
            }
        }
    }
}

?>
